<template>
  <div class="content-container">
    <header class="header">
      <el-input
          v-model="searchQuery"
          placeholder="搜索资源"
          prefix-icon="el-icon-search"
          suffix-icon="el-icon-circle-close"
          clearable
          @clear="handleClear"
          @keyup.enter="handleSearch"
          class="search-input"
      ></el-input>
      <el-button type="primary" icon="el-icon-search" circle @click="handleSearch"> 搜索</el-button>
    </header>

    <section class="filter-section">
      <el-row class="menu-row" v-for="(category, index) in categories" :key="index">
        <span class="label">{{ category.label }}</span>
        <el-button
            v-for="item in category.items"
            :key="item"
            type="text"
            :class="{ active: selectedItems[category.key] === item }"
            @click="selectItem(category.key, item)"
        >
          {{ item }}
        </el-button>
      </el-row>
    </section>

    <section class="breadcrumb-section">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item v-for="(item, key) in selectedItems" :key="key" :to="{}">
          {{ item }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </section>

    <section class="video-section">
      <div class="video-list" v-if="paginatedVideos.length > 0">
        <Card
            v-for="video in paginatedVideos"
            :key="video.resourceId"
            :resourceId="video.resourceId"
            @click="playVideo(video.resourceId)"
        />
      </div>
      <div v-else class="no-videos">
        <p>没有相关视频。</p>
      </div>
    </section>

    <footer class="pagination-section">
      <el-pagination
          v-model:current-page="paginationData.pageNum"
          :page-size="paginationData.pageSize"
          :small="true"
          :background="true"
          layout="total, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </footer>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed, reactive } from 'vue';
import { resourceApi } from '@/api/resourceApi';
import Card from "@/components/CardTwo.vue";
import { useRouter } from "vue-router";

const searchQuery = ref(''); // 用于搜索文本
const paginationData = reactive({
  pageNum: 1, // 当前页数
  pageSize: 8, // 每页显示的数量
});
const total = ref(0); // 视频总数
const videos = ref([]); // 存储视频资源

const categories = [
  { label: '学段', key: 'level', items: ['小学', '初中', '高中'] },
  { label: '学科', key: 'subject', items: ['语文', '数学', '英语', '道德与法治', '科学', '艺术·音乐', '艺术·美术', '体育与健康', '劳动与技术'] },
  { label: '版本', key: 'version', items: ['统编版'] },
  { label: '册次', key: 'semester', items: ['必修上册', '必修下册', '选择性必修上册', '选择性必修中册', '选择性必修下册'] }
];

const selectedItems = reactive({
  level: '小学',
  subject: '语文',
  version: '统编版',
  semester: '必修上册'
});

// 计算属性：分页后的视频列表
const paginatedVideos = computed(() => {
  const start = (paginationData.pageNum - 1) * paginationData.pageSize;
  const end = start + paginationData.pageSize;
  return videos.value.slice(start, end); // 返回当前页的视频数据
});

// 根据选择的条件加载视频
const fetchVideos = async () => {
  try {
    let query = `${selectedItems.level}/${selectedItems.subject}`;

    // 如果有搜索关键词，添加到查询条件中
    if (searchQuery.value) {
      query += `/${searchQuery.value}`;
    }

    const response = await resourceApi.es(query, paginationData.pageNum, paginationData.pageSize);
    videos.value = response.resources;
    total.value = response.total; // 更新视频总数
  } catch (error) {
    console.error('加载视频时发生错误:', error);
  }
};

// 使用 watch 监听选择项和搜索关键词的变化
watch([() => selectedItems.level, () => selectedItems.subject, () => selectedItems.version, () => selectedItems.semester, searchQuery], fetchVideos);

// 选择函数
const selectItem = (key, item) => {
  selectedItems[key] = item;
  paginationData.pageNum = 1; // 切换分类后重置为第一页
  fetchVideos(); // 重新加载视频
};

// 播放视频的函数
const playVideo = (id) => {
  const router = useRouter(); // 获取 router 实例
  router.push({ name: 'videoPlayer', params: { resourceId: id } }); // 使用 router 实例
};

// 搜索处理函数
const handleSearch = async () => {
  paginationData.pageNum = 1; // 搜索后重置为第一页
  await fetchVideos(); // 调用加载视频的方法
};

// 清空搜索
const handleClear = () => {
  searchQuery.value = '';
  fetchVideos(); // 重新加载视频
};

// 分页处理函数
const handleSizeChange = (newSize) => {
  paginationData.pageSize = newSize;
  paginationData.pageNum = 1; // 重置为第一页
  fetchVideos(); // 重新加载视频
};

const handleCurrentChange = (newPage) => {
  paginationData.pageNum = newPage; // 更新当前页
  fetchVideos(); // 重新加载视频
};

// 该代码需要在组件挂载时执行
fetchVideos(); // 初始请求视频
</script>

<style scoped>
.content-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
  margin-right: 10px;
  height: 40px;
  border-radius: 20px;
  font-size: 16px;
}

.filter-section {
  margin-bottom: 20px;
}

.menu-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.label {
  min-width: 50px;
  color: #999;
  font-size: 14px;
  margin-right: 10px;
}

.menu-row .el-button {
  font-size: 14px;
  margin-right: 8px;
  padding: 8px 16px;
  border-radius: 20px;
}

.el-button.active {
  background-color: #e6f7ff;
  color: #40a9ff;
}

.breadcrumb-section {
  margin-bottom: 20px;
}

.video-section {
  margin-bottom: 20px;
}

.video-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.no-videos {
  text-align: center;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.pagination-section {
  text-align: center;
}

@media (max-width: 768px) {
  .search-input {
    width: 100%;
  }

  .menu-row {
    flex-wrap: wrap;
  }

  .label {
    margin-bottom: 8px;
  }

  .menu-row .el-button {
    margin-bottom: 8px;
  }
}
</style>